<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/19 0019
 * Time: 10:31
 */

namespace frontend\controllers;
// header("Access-Control-Allow-Origin:http://medicals.qingguo188.com");
// header("Access-Control-Allow-Origin:http://localhost:8080");
header("Access-Control-Allow-Methods:POST,GET");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Credentials: true");
use common\models\User;
use common\models\UserSecondary;
use common\models\UserDrug;
use common\models\UserDrugWarehouse;
use common\models\UserSupplier;
use Yii;
// use yii\web\Controller;
use yii\data\Pagination;
use frontend\controllers\BaseController;
/**
 * User controller
 */
class UserDrugWarehouseController extends BaseController
{

    public function beforeAction($action)
    {
        if ($action->id == 'showlist' || $action->id == 'create' || $action->id == 'update'|| $action->id == 'delete'|| $action->id == 'search') {
            $this->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
        ];

    }
    /**
     * show
     *
     * return json
     */
    public function actionShowlist()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //判断用户是不是二级用户,如果是获得一级用户的id
                $data = $this->doifuserid($data1);
                //获得用户的药品信息  获得用户的供货商信息 还有模糊查询
                $arr = [];
                $druglist = UserDrugWarehouse::find()->where('user_id = :user_id and status = :status',[':user_id'=>$data['id'],':status'=>1])->all();
                $count = count($druglist);
                $j = 0;
                for($i = 0;$i<$count;$i++){
                    //(1)药品字典 查询药品名称
                    $zidian = UserDrug::find()->where("status=:status and id = ".$druglist[$i]['user_drug_id'],[':status'=>1])->andwhere("name like '%".$data1['name']."%'
                                                                                                                 or barcode like '%".$data1['name']."%'
                                                                                                                 or name_intro like '%".$data1['name']."%'
                                                                                                                 or spell_intro like '%".$data1['name']."%'")->one();
                    //(1.1)查询该药品字典下的药品库存
                    $nums = 0;
                    $drugs = UserDrugWarehouse::find()->where('user_id = :user_id and status = :status and user_drug_id = :user_drug_id',[':user_id'=>$data['id'],':status'=>1,':user_drug_id'=>$zidian['id']])->all();
                    $count1 = count($drugs);
                    for($k = 0;$k < $count1;$k++){
                        $nums += $drugs[$k]['num'];
                    }
                    //(2)判断药品字典是否存在
                    if($zidian){
                        //(3)如果药品字典存在,接着查询供货商的信息
                        $supplier = UserSupplier::find()->where("id = :id",[":id"=>$druglist[$i]['user_supplier_id']])->one();
                        $arr[$j]['zidian_id'] = $zidian['id'];
                        $arr[$j]['drug_id'] = $druglist[$i]['id'];
                        $arr[$j]['name'] = $zidian['name'];
                        $arr[$j]['name_intro'] = $zidian['name_intro'];
                        $arr[$j]['specification'] = $zidian['specification'];
                        $arr[$j]['unit'] = $zidian['unit'];
                        $arr[$j]['shape'] = $zidian['shape'];
                        $arr[$j]['supplier'] = $supplier['name'];
                        $arr[$j]['barcode'] = $zidian['barcode'];
                        $arr[$j]['coding'] = $zidian['coding'];
                        $arr[$j]['spell_intro'] = $zidian['spell_intro'];
                        $arr[$j]['num'] =$druglist[$i]['num'];
                        $arr[$j]['nums'] =$nums;
                        $arr[$j]['in_price'] =$druglist[$i]['in_price'];
                        $arr[$j]['out_price'] =$druglist[$i]['out_price'];
                        $arr[$j]['produce_time'] =$druglist[$i]['produce_time'];
                        $arr[$j]['expired_time'] =$druglist[$i]['expired_time'];
                        $j++;
                    }
                }
                //获得查询
                return  $this->getjson(1,$arr);

            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * show
     *
     * return json
     */
    public function actionSearch()
    {
        if(Yii::$app->request->isPost) {
            $data1 = Yii::$app->request->post();
            //获得当前登录的用户
            $data = $this->doifuserid($data1);
            if ($data1) {
                $arr = [];
                //获得用户药品字典信息
                $list = UserDrug::find()->where('barcode = :barcode and status = :status and user_id = :user_id', [":status" => 1, ":barcode" => $data1['barcode'],":user_id" => $data['id']])->one();
                if($list) {
                    //获得用户的供货单位
                    $supplier = UserSupplier::find()->where('id = :id and user_id = :user_id', [':id' => $list['vender_id'], ':user_id' => $data['id']])->one();
                    //获得用户最近添加的药品信息
                    $drug = UserDrugWarehouse::find()
                        ->where('user_id = :user_id and user_drug_id = :userdrugid and user_supplier_id = :usersupplierid and status = :status', [':user_id' => $data['id'], ':userdrugid' => $list['id'], ':status' => 1, ':usersupplierid' => $supplier['id']])
                        ->orderBy('id desc')
                        ->one();
                    $drugs =  UserDrugWarehouse::find()
                        ->where('user_id = :user_id and user_drug_id = :userdrugid and user_supplier_id = :usersupplierid and status = :status', [':user_id' => $data['id'], ':userdrugid' => $list['id'], ':status' => 1, ':usersupplierid' => $supplier['id']])
                        ->all();
                    $arr['info']['supplier'] = $supplier['name'];
                    $arr['info']['name'] = $list['name'];
                    $arr['info']['specification'] = $list['specification'];
                    $arr['info']['unit'] = $list['unit'];
                    $arr['info']['shape'] = $list['shape'];
                    $arr['info']['coding'] = $list['coding'];
                    $arr['info']['name_intro'] = $list['name_intro'];
                    $arr['info']['spell_intro'] = $list['spell_intro'];
                    if (!$drug) {
                        $arr['info']['in_price'] = '';
                        $arr['info']['out_price'] = '';
                        $arr['info']['product_coding'] = '';
                        $arr['info']['product_time'] = '';
                        $arr['info']['expired_time'] = '';
                        $arr['info']['num'] = 0;
                        $arr['info']['nums'] = 0;
                        $arr['info']['source'] = '';
                    } else {
                        $num = 0;
                        foreach($drugs as $key=>$val){
                            $num += $val['num'];
                        }
                        $arr['info']['in_price'] = $drug['in_price'];
                        $arr['info']['out_price'] = $drug['out_price'];
                        $arr['info']['source'] = $drug['source'];
                        $arr['info']['product_coding'] = $drug['product_coding'];
                        $arr['info']['produce_time'] = $drug['produce_time'];
                        $arr['info']['expired_time'] = $drug['expired_time'];
                        $arr['info']['nums'] = $num;
                        $arr['info']['num'] = 0;
                    }
                    //获得用户的药品厂商
                    $arr['supplier'] = $this->getSupplier($data['id']);
                    return $this->getjson(1,$arr);
                }else{
                    return $this->getjson(3,$arr);
                }
            } else {
                return $this->getjson(0, '参数不能为空');
            }
        }
    }

    /**
     * craate
     *
     * return json
     */
    public function actionCreate()
    {
        if(Yii::$app->request->isPost) {
            $data1 = Yii::$app->request->post();
            //获得当前登录的用户
            $data = $this->doifuserid($data1);
            if ($data1) {
                //(1)判断厂家是否存在  不存在添加数据库
                $supplier = UserSupplier::find()->where('name = :name',[':name'=>$data1['supplier']])->one();
                $user_suppiler_id = $supplier['id'];
                if(!$supplier){
                    $supplier = new  UserSupplier();
                    $supplier->name = $data1['supplier'];
                    $supplier->user_id = $data['id'];
                    if(!$supplier->save()){
                        return $this->getjson(0, '添加数据失败,请重试');
                    }
                    $user_suppiler_id = $supplier->id;
                }
                //(2)判断用户词典是否存在
                $userdruglsit = UserDrug::find()->where('barcode = :barcode',[':barcode'=>$data1['barcode']])->one();
                if($userdruglsit){
                    $user_drug_id = $userdruglsit['id'];
                }else{
                    $model = new UserDrug();
                    $model->barcode = $data1['barcode'];
                    $model->user_id = $data['id'];
                    $model->name = $data1['name'];
                    $model->name_intro = $data1['name_intro'];
                    $model->specification = $data1['specification'];
                    $model->unit = $data1['unit'];
                    $model->coding = $data1['coding'];
                    $model->spell_intro = $data1['spell_intro'];
                    if(!$model->save()){
                        return $this->getjson(0, '添加数据失败,请重试');
                    }
                    $user_drug_id = $model['id'];

                }
                //(3)添加用户药品信息
                $userdrugwarehouse = new UserDrugWarehouse();
                $userdrugwarehouse->user_id = $data['id'];
                $userdrugwarehouse->user_drug_id = $user_drug_id;
                $userdrugwarehouse->user_supplier_id = $user_suppiler_id;
                $userdrugwarehouse->num = $data1['num'];
                $userdrugwarehouse->source = $data1['source'];
                $userdrugwarehouse->in_price = $data1['in_price'];
                $userdrugwarehouse->out_price = $data1['out_price'];
                $userdrugwarehouse->expired_time = $data1['expired_time'];
                $userdrugwarehouse->produce_time = $data1['produce_time'];
                if(!$userdrugwarehouse->save()){
                    return $this->getjson(0, '添加数据失败,请重试');
                }
                return $this->getjson(1, '添加成功');

            } else {
                return $this->getjson(0, '参数不能为空');
            }
        }
    }

    /**
     * update
     *
     * return json
     */
    public function actionUpdate()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //获得当前登录的用户
                $data = $this->doifuserid($data1);
                //(1)判断厂家是否存在,不存在否则添加
                $usersupplier = new UserSupplier();
                $supplier = $usersupplier::find()->where('name = :name',[':name'=>$data1['supplier']])->one();
                if(!$supplier){
                    $usersupplier->user_id = $data['id'];
                    $usersupplier->name = $data1['supplier'];
                    if($usersupplier->save()){
                        $user_supplier_id = $usersupplier->id;
                    }else{
                        return $this->getjson(0,'添加数据库失败');
                    }
                }else{
                    $user_supplier_id = $supplier['id'];
                }
                //(2)更新药品字典的信息
                $userdruglist = UserDrug::findOne($data1['zidian_id']);
                $userdruglist->name = $data1['name'];
                $userdruglist->name_intro = $data1['name_intro'];
                $userdruglist->specification = $data1['specification'];
                $userdruglist->unit = $data1['unit'];
                $userdruglist->shape = $data1['shape'];
                $userdruglist->barcode = $data1['barcode'];
                $userdruglist->spell_intro = $data1['spell_intro'];
                $userdruglist->coding = $data1['coding'];
                if(!$userdruglist->save()){
                    return $this->getjson(0,'添加数据库失败');
                }
                //(3)更新药品的信息
                $userdrugwarehouser = UserDrugWarehouse::findOne($data1['drug_id']);
                $userdrugwarehouser->num = $data1['num'];
                $userdrugwarehouser->in_price = $data1['in_price'];
                $userdrugwarehouser->out_price = $data1['out_price'];
                $userdrugwarehouser->expired_time = $data1['expired_time'];
                $userdrugwarehouser->user_supplier_id = $user_supplier_id;
                $userdrugwarehouser->produce_time = $data1['produce_time'];
                if(!$userdrugwarehouser->save()){
                    return $this->getjson(0,'添加数据库失败');
                }
                return $this->getjson(1,'更新成功');
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * delete
     *
     * return json
     */

    public function actionDelete()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1) {
                //(1)删除用户的药品表中的数据
                $list = UserDrugWarehouse::findOne($data1['drug_id']);
                if(!$list){
                    return $this->getjson(0,'传入的参数错误');
                }
                if(!$list->delete()){
                    return $this->getjson(0,'删除失败,请重试');
                }
                return $this->getjson(1,'删除成功');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * 判断是否是二级用户,是的话获得一级用户的id
     */
    public  function  doifuserid($data)
    {
        if($data['level'] == 2){
            $userInfo = UserSecondary::find()->where('id = :id',[':id'=>$data['id']])->one();
            $data['id'] = $userInfo['user_id'];
            if(!$userInfo){
                return $this->getjson(0, '获取用户信息失败');
            }
            $data['id'] = $userInfo['user_id'];
        }
        if(!$data['id']){
            return $this->getjson(0, '用户尚未登录');
        }
        return  $data;
    }

    /**
     * 获得用户的所有的供货商
     */
    public function getSupplier($id)
    {
        $arr = UserSupplier::find()->where('user_id = :user_id',[':user_id'=>$id])->all();
        $list = [];
        if($arr){
            $count = count($arr);
            for($i = 0;$i<$count;$i++){
                $list[$i]['id'] = $arr[$i]['id'];
                $list[$i]['name'] = $arr[$i]['name'];
            }
        }
        return $list;
    }

}





















